#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
  pid_t id = fork();
  if(id == 0)
  {
    printf("I am a Child Process,pid:%d,ppid:%d\n",getpid(),getppid());
    exit(1);
  }
  else if(id < 0)
  {
      perror("fork");
      return 1;
  }
  else
  {
    while(1)
    {
      pid_t ret = wait(NULL);
      if(ret < 0)
      {
        printf("wait failed\n");
        break;
      }
      else if(ret >0)
      {
        printf("进程是正常跑完的, 退出码:%d\n",ret);
        break;
      }
      else
      {
           /*printf("进程还结束，请等待哦\n");
           break;*/ 
					 int status =0;
           while(1)
           { //轮询
               pid_t ret = waitpid(id, &status, WNOHANG); //非阻塞
               if(ret > 0)
               {
                // 7F: 0111 1111
                // printf("wait success, ret: %d, exit sig: %d, exit code: %d\n", ret, status&0x7F, (status>>8)&0xFF);
                  if(WIFEXITED(status))
                  {
                      printf("进程是正常跑完的, 退出码:%d\n", WEXITSTATUS(status));
                  }
                  else
                  {
                      printf("进程出异常了\n");
                  }
                  break;
               }
               else if(ret < 0)
                {
                  printf("wait failed!\n");
                  break;
                }
                else
                {
                  //ret == 0
                  printf("你好了没？子进程还没有退出，我在等等...\n");
                  sleep(1);
                }
           }
      }
  }
  }
  return 0;
 }
